/**
 * 性能优化使用示例
 * 
 * 展示如何使用空间分区和批量处理优化逻辑系统
 * 
 * @author AI Assistant
 * @date 2025-11-26
 */

import { ecs } from "../../../core/ecs/ECS";
import { InterpolatedTransform } from "../component/InterpolatedTransform";
import { VelocityComponent } from "./MovementLogicSystem";
import { CollisionComponent } from "./OptimizedCollisionSystem";
import { optimizedMovementLogicSystem } from "./OptimizedMovementLogicSystem";
import { optimizedCollisionSystem } from "./OptimizedCollisionSystem";

/**
 * 性能对比测试
 */
export async function performanceComparisonTest(): Promise<void> {
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('📊 性能优化对比测试');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // 创建测试实体
    const entityCount = 1000;
    console.log(`创建 ${entityCount} 个测试实体...`);
    
    const entities: ecs.Entity[] = [];
    
    for (let i = 0; i < entityCount; i++) {
        const entity = ecs.getEntity(ecs.Entity);
        
        // 添加组件
        const transform = entity.add(InterpolatedTransform);
        const velocity = entity.add(VelocityComponent);
        const collision = entity.add(CollisionComponent);
        
        // 随机位置
        transform.setPosition(
            (Math.random() - 0.5) * 2000,
            (Math.random() - 0.5) * 2000,
            0
        );
        transform.syncPreviousFrame();
        
        // 随机速度
        velocity.setVelocity(
            (Math.random() - 0.5) * 200,
            (Math.random() - 0.5) * 200
        );
        
        // 随机碰撞半径
        collision.radius = 20 + Math.random() * 30;
        
        entities.push(entity);
    }
    
    console.log(`✅ 创建完成\n`);
    
    // 测试 1: 移动系统性能
    console.log('━━━━ 测试 1: 移动系统性能 ━━━━');
    testMovementPerformance(entities);
    
    // 测试 2: 碰撞检测性能
    console.log('\n━━━━ 测试 2: 碰撞检测性能 ━━━━');
    testCollisionPerformance(entities);
    
    // 测试 3: 空间网格统计
    console.log('\n━━━━ 测试 3: 空间网格统计 ━━━━');
    const spatialGrid = optimizedMovementLogicSystem.getSpatialGrid();
    const stats = spatialGrid.getStats();
    console.log(`网格数量: ${stats.totalCells}`);
    console.log(`实体总数: ${stats.totalEntities}`);
    console.log(`平均每网格实体数: ${stats.averageEntitiesPerCell.toFixed(2)}`);
    console.log(`最大网格实体数: ${stats.maxEntitiesInCell}`);
    
    console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('✅ 性能测试完成');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
}

/**
 * 测试移动系统性能
 */
function testMovementPerformance(entities: ecs.Entity[]): void {
    const iterations = 100;
    const dt = 0.05; // 固定时间步长
    
    // 预热
    for (let i = 0; i < 10; i++) {
        optimizedMovementLogicSystem.update(dt);
    }
    
    // 测试
    const startTime = performance.now();
    for (let i = 0; i < iterations; i++) {
        optimizedMovementLogicSystem.update(dt);
    }
    const endTime = performance.now();
    
    const totalTime = endTime - startTime;
    const avgTime = totalTime / iterations;
    
    console.log(`迭代次数: ${iterations}`);
    console.log(`总耗时: ${totalTime.toFixed(2)}ms`);
    console.log(`平均耗时: ${avgTime.toFixed(3)}ms`);
    console.log(`实体数量: ${entities.length}`);
    console.log(`每实体耗时: ${(avgTime / entities.length * 1000).toFixed(3)}μs`);
}

/**
 * 测试碰撞检测性能
 */
function testCollisionPerformance(entities: ecs.Entity[]): void {
    // 设置移动系统引用
    optimizedCollisionSystem.setMovementSystem(optimizedMovementLogicSystem);
    
    const iterations = 10; // 碰撞检测较慢，减少迭代次数
    const dt = 0.05;
    
    // 预热
    for (let i = 0; i < 2; i++) {
        optimizedMovementLogicSystem.update(dt);
        optimizedCollisionSystem.update(dt);
    }
    
    // 测试
    const startTime = performance.now();
    for (let i = 0; i < iterations; i++) {
        optimizedMovementLogicSystem.update(dt);
        optimizedCollisionSystem.update(dt);
    }
    const endTime = performance.now();
    
    const totalTime = endTime - startTime;
    const avgTime = totalTime / iterations;
    
    console.log(`迭代次数: ${iterations}`);
    console.log(`总耗时: ${totalTime.toFixed(2)}ms`);
    console.log(`平均耗时: ${avgTime.toFixed(3)}ms`);
    console.log(`实体数量: ${entities.length}`);
    
    // 计算理论碰撞检查次数（使用空间分区）
    const spatialGrid = optimizedMovementLogicSystem.getSpatialGrid();
    const stats = spatialGrid.getStats();
    const avgChecks = stats.averageEntitiesPerCell * stats.averageEntitiesPerCell * stats.totalCells;
    const bruteForceChecks = entities.length * entities.length;
    
    console.log(`\n性能对比:`);
    console.log(`  暴力方法检查次数: ${bruteForceChecks.toLocaleString()}`);
    console.log(`  空间分区检查次数: ~${Math.round(avgChecks).toLocaleString()}`);
    console.log(`  性能提升: ~${(bruteForceChecks / avgChecks).toFixed(0)}x`);
}

/**
 * 使用示例
 */
export const OptimizationExamples = {
    performanceTest: performanceComparisonTest,
    
    /**
     * 创建优化的移动实体
     */
    createOptimizedEntity: (x: number, y: number, vx: number, vy: number): ecs.Entity => {
        const entity = ecs.getEntity(ecs.Entity);
        
        const transform = entity.add(InterpolatedTransform);
        transform.setPosition(x, y, 0);
        transform.syncPreviousFrame();
        
        const velocity = entity.add(VelocityComponent);
        velocity.setVelocity(vx, vy);
        
        return entity;
    },
    
    /**
     * 创建带碰撞的实体
     */
    createCollisionEntity: (x: number, y: number, radius: number): ecs.Entity => {
        const entity = ecs.getEntity(ecs.Entity);
        
        const transform = entity.add(InterpolatedTransform);
        transform.setPosition(x, y, 0);
        transform.syncPreviousFrame();
        
        const collision = entity.add(CollisionComponent);
        collision.radius = radius;
        
        return entity;
    },
    
    /**
     * 查询附近实体
     */
    findNearbyEntities: (x: number, y: number, radius: number): ecs.Entity[] => {
        return optimizedMovementLogicSystem.getNearbyEntities(x, y, radius);
    }
};

